<script setup lang="ts">
import { useIntersectionObserver } from "@vueuse/core";
import { computed, onUnmounted, ref } from "vue";
const itemValue = defineModel("itemValue");
const formItemRef = ref(null);
const isRender = ref(false);
const props = withDefaults(
  defineProps<{
    status?: number;
    statusRange?: string;
    disabled?: boolean;
    itemProps: Array<string | number>;
    validated: boolean;
    isRequired?: boolean;
  }>(),
  {
    status: 1,
    statusRange: "",
    disabled: false,
    isRequired: true
  }
);
const { stop } = useIntersectionObserver(
  formItemRef,
  ([{ isIntersecting }]) => {
    isRender.value = isIntersecting;
    if (props.validated) {
      formItemRef.value.validate();
    }
  },
  {
    threshold: 0
  }
);
onUnmounted(() => {
  stop();
});
const options = computed(() => {
  const range =
    props["statusRange"]
      ?.split(",")
      ?.filter(item => !!item) // 筛选不为空
      ?.map(item => ({ label: item, value: item })) || [];
  return range;
});
const handleBlur = (event: any) => {
  itemValue.value = event?.target?.value ? Number(event?.target?.value) : null;
};
const handleChange = (value: any) => {
  if (props.status === 2 && (typeof value === "string" || typeof value === "number")) {
    itemValue.value = value ? Number(value) : value;
  }
};
</script>
<template>
  <px-form-item
    ref="formItemRef"
    label=""
    label-width="0px"
    class="form-item-in-table"
    :prop="itemProps"
    :inline-message="true"
    :rules="[{ required: isRequired, message: '巡检结果不能为空', trigger: ['change', 'blur'] }]"
  >
    <div class="form-item-content">
      <px-input
        v-if="status === 1"
        v-model="itemValue"
        class="cell-action"
        :disabled="disabled"
        maxLength="50"
        placeholder="请输入"
        clearable
        @blur="itemValue = $event.target.value.trim()"
        @change="handleChange"
      />
      <px-input-number
        v-if="status === 2"
        :model-value="itemValue"
        class="cell-action"
        style="width: 100%"
        :disabled="disabled"
        clearable
        :max="999999999999999"
        @blur="handleBlur"
        @change="handleChange"
      />
      <px-radio-group v-if="status === 3 && statusRange" v-model="itemValue" class="cell-action" :disabled="disabled" @change="handleChange">
        <px-radio v-for="(item, index) in options" :key="index" :label="item.value">{{ item.label }}</px-radio>
      </px-radio-group>
      <px-select
        v-if="status === 4 && statusRange"
        v-model="itemValue"
        filterable
        clearable
        class="cell-action"
        style="width: 100%"
        :disabled="disabled"
        placeholder="请选择"
        @change="handleChange"
      >
        <px-option v-for="(item, index) in options" :key="index" :label="item.label" :value="item.value" />
      </px-select>
    </div>
  </px-form-item>
</template>
<style lang="scss" scoped>
.form-item-in-table {
  margin-bottom: 0;
}
</style>
